<?php

namespace app\admin\controller\dashboard;

use app\admin\model\DeviceModel;
use app\admin\model\DeviceTrendsModel;
use app\admin\model\UserModel;
use app\common\controller\Backend;
use app\common\Helper\AppTools;
use think\Request;

class Index extends Backend
{
    // 获取统计&动态列表
    public function database(Request $request)
    {
        $param = $request->param();
        $data = json_decode($param['data'], true);
        $currpage = $data['page'];
        $pagesize = $data['size'];
        $userModel = new UserModel();
        $deviceModel = new DeviceModel();
        $deviceTrendsModel = new DeviceTrendsModel();
        $stat = [];
        // 统计用户数量
        $stat['user'] = $userModel->getCount([]);
        // 统计设备数量
        $stat['device'] = $deviceModel->getCount(['datastatus' => $deviceModel::NORMAL_DATASTATUS]);
        // 统计在线设备数量
        $stat['online'] = $deviceModel->getCount(['datastatus' => $deviceModel::NORMAL_DATASTATUS, 'is_line' => $deviceModel::DEVICE_ONLINE]);
        // 统计离线设备数量
        $stat['offline'] = $deviceModel->getCount(['datastatus' => $deviceModel::NORMAL_DATASTATUS, 'is_line' => $deviceModel::DEVICE_OFFLINE]);
        // 统计动态数量
        $trendsList = $deviceTrendsModel->getSelect(['is_new' => $deviceTrendsModel::YES_NEW, 'datastatus' => $deviceTrendsModel::NORMAL_DATASTATUS]);
        $where = [
            'lc_device_trends.is_new' => $deviceTrendsModel::YES_NEW,
            'lc_device_trends.datastatus' => $deviceTrendsModel::NORMAL_DATASTATUS,
            'lc_device.datastatus' => $deviceModel::NORMAL_DATASTATUS
        ];
        $field = ['lc_device.id as device_id,lc_device.device_name,lc_device_trends.itime,lc_device_trends.address,lc_device_trends.trends_data'];
        $trendsList = $deviceTrendsModel->table('lc_device_trends,lc_device')
            ->where('lc_device_trends.device_id=lc_device.id')
            ->where($where)
            ->field($field)
            ->page($currpage, $pagesize)
            ->select()->toArray();
        foreach ($trendsList as &$val) {
            $locate = json_decode($val['trends_data'], true);
            $loc = explode(',', $locate['gps']);
            $val['lng'] = $loc[1];
            $val['lat'] = $loc[0];
        }
        // if (count($trendsList) < 1) return success([]);
        $count = $deviceTrendsModel->table('lc_device_trends,lc_device')
            ->where('lc_device_trends.device_id=lc_device.id')
            ->where($where)
            ->count();

        $list = AppTools::morePage($trendsList, $count, $currpage, $pagesize);
        $data = [
            'stat' => $stat,
            'total_num' => $count,
            'data' => $list,
        ];
        return success($data);
    }

    // 获取所有动态列表（is_new =1的）
    public function trendsList(Request $request)
    {
    }
}
